<?php
class Cache {
	const CACHE_FILE = 1;
	const CACHE_MEMC = 2;
	
	protected $_fileObj = null;
	protected $_memcObj = null;
	
	public function __construct(Config $config) {
		if ($config->file->enabled) {
			$this->_fileObj = new Cache_File($config->file->options);
		}
		if ($config->memcache->enabled) {
			$class = "Cache_{$config->memcache->type}";
			if (class_exists($class)) {
				$this->_memcObj = new $class($config->memcache->options);
			}
		}
	}
	
	/**
	 * 写入缓存
	 *
	 * @param string $key
	 * @param mixed $value
	 * @param int $ttl
	 * @param int $ctype
	 * @return boolean
	 */
	public function set($key, $value, $ttl = 0, $ctype = 3) {
		if (($ctype & self::CACHE_MEMC) && $this->_memcObj) {
			if ($this->_memcObj->set($key, $value, $ttl)) {
				return true;
			}
		}
		if (($ctype & self::fileObj) && $this->_fileObj) {
			if ($this->_fileObj->set($key, $value, $ttl)) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 读取缓存
	 *
	 * @param string $key
	 * @param int $ctype
	 * @return mixed
	 */
	public function get($key, $ctype = 3) {
		if (($ctype & self::CACHE_MEMC) && $this->_memcObj) {
			if (false !== ($value = $this->_memcObj->get($key))) {
				return $value;
			}
		}
		if (($ctype & self::fileObj) && $this->_fileObj) {
			if (false !== ($value = $this->_fileObj->get($key))) {
				return $value;
			}
		}
		return false;
	}
	
	/**
	 * 删除缓存
	 *
	 * @param string $key
	 */
	public function rm($key) {
		if ($this->_memcObj) $this->_memcObj->rm($key);
		if ($this->_fileObj) $this->_fileObj->rm($key);
	}
	
	/**
	 * 清空缓存
	 *
	 * @param int $ctype
	 */
	public function clear($ctype = 3) {
		if (($ctype & self::CACHE_MEMC) && $this->_memcObj) {
			$this->_memcObj->clear();
		}
		if (($ctype & self::fileObj) && $this->_fileObj) {
			$this->_fileObj->clear();
		}
	}
}
